package com.whq.controller;

import com.alibaba.fastjson.JSONObject;
import com.whq.constant.Constant;
import com.whq.entity.Address;
import com.whq.entity.Member;
import com.whq.entity.User;
import com.whq.service.MemberService;
import com.whq.service.weixin.EventsService;
import com.whq.service.weixin.factory.WechatEventFactory;
import com.whq.utils.*;
import com.whq.weixin.entity.W3AccessToken;
import com.whq.weixin.entity.WeChatReceiveMsg;
import com.whq.weixin.entity.WeiXinCallBack;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URLEncoder;
import java.util.Date;
import java.util.List;

/**
 * Created by qpx on 2017/11/29.
 */
@Controller
public class WxController  {

    private Logger logger = LoggerFactory.getLogger(this.getClass());


    @Autowired
    MemberService memberService;



    @Bean(initMethod="init",destroyMethod="destroyMethod")
    @Scope(value = "prototype")
    public User user(){
        User user = new User();
        user.setAddress(address());
        return user;
    }

    @Bean
    public Address address(){
        return new Address();
    }


    /**
     * 验证token
     *
     */
    @RequestMapping("/weixin")
    @ResponseBody
    public String weixin(WeiXinCallBack weiXinCallBack, HttpServletRequest request, HttpServletResponse response) throws IOException {

        //验证请求是否是微信服务器发送过来的开始
        logger.info("weixin callback begin......");
        PropertiesLoader load = new PropertiesLoader("weixin.properties");
        String token = load.getProperty("token");

        String signature = weiXinCallBack.getSignature();// 微信加密签名
        String timestamp = weiXinCallBack.getTimestamp(); //时间戳
        String nonce = weiXinCallBack.getNonce();//随机数

        String tmpStr = "";
        String returnMessage = "success";
        try {
            tmpStr = WeiXinUtils.getSHA1(token, timestamp, nonce);
            if(!tmpStr.equals(signature)){
                return "error";
            }
            String method = request.getMethod();
            logger.info("@@@@@@@@@@@@method:"+method);
            if(method.equals("GET")){
                logger.info("@@@@@@@@@@@@getEchostr:"+weiXinCallBack.getEchostr());
                return weiXinCallBack.getEchostr();
            }
            //验证请求是否是微信服务器发送过来的结束
            WeChatReceiveMsg msg = WeiXinUtils.getMsg(request.getInputStream());
            this.logger.info("微信回掉消息为>>>>>>>>>>>:" + JSONObject.toJSONString(msg));
            String msgType = msg.getMsgType();

            if (msgType.equals("event")) {
                //接收事件消息
                String event = msg.getEvent();
                EventsService eventsService = WechatEventFactory.create(event);
                if(eventsService!=null){
                    returnMessage = eventsService.response(msg);
                }
            }else {//接收普通消息
                msg.setEventKey("but_lianxikefu");
                EventsService eventsService = WechatEventFactory.create("click");
                if(eventsService!=null){
                    returnMessage = eventsService.response(msg);
                }
            }

        } catch (Exception e1) {
            logger.error("callback validate exception {}",e1);
            this.returnMessage(returnMessage, response);
        }
        this.returnMessage(returnMessage, response);
        logger.info("weixin callback end......");
        return null;
    }

    @RequestMapping(value="/toLogin",method= RequestMethod.GET)
    public String toLogin(HttpServletRequest request,HttpServletResponse response,String code,ModelMap map){
        String openidKey= Constant.load.getProperty("openidKey");
        String openid = CookieUtils.getCookie(request, openidKey);
        try {
            if(StringUtils.isBlank(openid)){
                if(StringUtils.isBlank(code)){
                    String url_prefix = Constant.load.getProperty("url_prefix");
                    String newurl = URLEncoder.encode(url_prefix + "/toLogin", "UTF-8");
                    String redirectPath = WeiXinUtils.getUrlBySnsapibase(newurl);
                    return "redirect:" + redirectPath;
                }
                W3AccessToken acctoken  =    WeiXinUtils.getAccToken(code);
                openid = acctoken.getOpenid();
                CookieUtils.setCookie(response, openidKey, openid,30*60*1000);
            }
        }  catch (Exception e) {
            e.printStackTrace();
        }
        map.put("openid",openid);
        return "login";
    }

    private void returnMessage(String message, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("utf-8");
        PrintWriter write = response.getWriter();
        write.print(message);
        write.flush();
        write.close();
    }


    @RequestMapping("/validateLogin")
    @ResponseBody
    public String validateLogin(HttpServletRequest request,HttpServletResponse response) throws Exception {
        String openidKey= Constant.load.getProperty("openidKey");
        String openid = CookieUtils.getCookie(request, openidKey);
        //CookieUtils.getCookie(request,"openid");
        String tel = request.getParameter("tel");

        //根据openid查询用户信息
        Member memberOpenid = new Member();
        memberOpenid.setOpenid(openid);
        List<Member> memberOpenidS = memberService.selectByCondition(memberOpenid);
        if(!CollectionUtils.isEmpty(memberOpenidS)){
            Member mopied = memberOpenidS.get(0);
            if(!tel.equals(mopied.getMobile())){
                return "该微信已经被其他手机所绑定";
            }else if(tel.equals(mopied.getMobile())){
                return "登录成功";
            }
        }


        Member member = new Member();
        member.setMobile(tel);
        List<Member> members = memberService.selectByCondition(member);
        if(CollectionUtils.isEmpty(members)){
            //进行注册
            member = new Member();
            member.setMobile(tel);
            member.setOpenid(openid);
            member.setCreated(new Date());
            member.setStatuts(1);
            memberService.insertSelective(member);
            CookieUtils.setCookie(response,"tel", MD5Util.MD5Encode(tel));
            JedisUtils.setObject(MD5Util.MD5Encode(tel),member,7200);

            return "登陆成功!";
        }else{
            Member member1 = members.get(0);
            if(StringUtils.isEmpty(member1.getOpenid())){
                member = new Member();
                member.setId(member1.getId());
                member.setOpenid(openid);

                memberService.updateByPrimaryKeySelective(member);
            }else if(tel.equals(member1.getMobile())){
                return "登陆成功";
            }else{
                return "该手机未绑定微信号";
            }
        }
        return "登陆成功";
    }

}
